package com.monster.servlet.user;

import com.alibaba.fastjson.JSON;
import com.monster.pojo.User;
import com.monster.service.UserService;
import com.monster.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/user/auto_login")
public class AutoLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Cookie[] cookies = request.getCookies();
        UserService us = new UserServiceImpl();
        PrintWriter out = response.getWriter();
        User user = null;
        String cookieId = null;
        int id = 0;

        for (int i = 0; i < cookies.length; i++) {
            if ("monster_user".equals(cookies[i].getName())) {
                cookieId = cookies[i].getValue();
                break;
            }
        }
        if (cookieId != null) {
            user = us.getUserById(Long.parseLong(cookieId));
            request.getSession().setAttribute("user", user);
            out.print(JSON.toJSONString(user));

        } else {
            out.print("no");
        }
        out.flush();
        out.close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
